<template>
  <div class="order">
    <div v-if="!isAdd">
      <div style="display: flex; justify-content: space-between">
        <el-form :inline="true" :model="formInline" class="demo-form-inline" ref="formInline">
          <el-form-item label="姓名" prop="searchName">
            <el-input v-model="formInline.searchName"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="formInline.phone"></el-input>
          </el-form-item>
          <el-form-item label="公司名称">
            <!-- <el-input v-model='formInline.companyName'></el-input> -->
            <!--  <p @click='showCompany' style='height: 40px;width: 200px;border: 1px solid #dcdfe6;border-radius:5px;text-align: center;'>{{formInline.companyName}}</p> -->
            <InputSearch />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">查询</el-button>
            <el-button type="default" @click="resetForm(formInline)">重置</el-button>
          </el-form-item>
        </el-form>
        <el-button type="primary" @click="addUser" class="addBtn">新增用户</el-button>
      </div>
      <div class="tables">
        <el-table ref="multipleTable" :data="tables" tooltip-effect="dark" style="width: 100%">
          <el-table-column type="index" label="序号" width="50"></el-table-column>
          <el-table-column prop="username" label="登录名"></el-table-column>
          <el-table-column prop="name" label="姓名"></el-table-column>
          <el-table-column prop="mobile" label="手机号"></el-table-column>
          <el-table-column prop="companyName" label="所属公司"></el-table-column>
          <el-table-column label="性别">
            <template slot-scope="scope">
              <span>{{scope.row.sex===1?'男':'女'}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="roles" label="角色">
            <template slot-scope="scope">
              <el-tag v-for="item in scope.row.roles" size="mini" :key="item.id">{{item.name}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="账号状态">
            <template slot-scope="scope">
              <span>{{scope.row.enable===1?'启用':'停用'}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="updateBy" label="创建人"></el-table-column>
          <el-table-column label="修改时间">
            <template slot-scope="scope">
              <span>{{$dateFormat(scope.row.updateAt,'yyyy-MM-dd hh:mm:ss')}}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column label="创建时间" >
          <template slot-scope="scope">{{ scope.row.date }}</template>
          </el-table-column>-->
          <el-table-column label="操作" width="200">
            <template slot-scope="scope">
              <el-button @click="handleUpdate(scope.row)" type="text" size="small">修改</el-button>
              <el-button @click="handleInitial(scope.row)" type="text" size="small">密码重置</el-button>
              <el-button @click="handleStopAccount(scope.row,0)" v-if="scope.row.enable===1" type="text" size="small">停用</el-button>
              <el-button @click="handleStopAccount(scope.row,1)" v-else type="text" size="small">启用</el-button>
              <el-button type="text" size="small" @click="handleDelet(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[10, 30, 50, 100]" :page-size="10" layout="total, sizes, prev, pager, next, jumper" :total="total1"></el-pagination>
    </div>
    <div class v-if="isAdd">
      <!--   <p class="commonColor" style='margin-bottom: 20px;font-size: 16px;color: blue' @class=''><i class='el-icon-arrow-left'></i>返回</p> -->
      <el-button type="text" size="medium" @click="goBack">返回</el-button>
      <!-- //这是用户新增 -->
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="登录名" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="ruleForm.sex">
            <el-radio label="男"></el-radio>
            <el-radio label="女"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="ruleForm.mobile"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="roles">
          <el-select v-model="defaultVal" placeholder="请选择角色" multiple @change="getSelectRole">
            <!-- <el-option label="管理员" value='管理员'></el-option>
            <el-option label="管理员111" value='JAVA大腿'></el-option>-->
            <el-option v-for="item in ruleForm.roles" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label='用户身份' prop='isAdmin'>
          <el-radio-group v-model="ruleForm.isAdmin">
            <el-radio label="普通用户"></el-radio>
            <el-radio label="管理员"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属公司">
          <!-- <el-input v-model='formInline.companyName'></el-input> -->
          <p @click="showCompany" :class="{err:showError}" style="height: 40px;width: 200px;border: 1px solid #dcdfe6;border-radius:5px;text-align: center;">{{formInline.companyName}}</p>
          <span v-if="showError" style="font-size: 12px;color:#f56c6c">请选择公司</span>
        </el-form-item>
        <el-form-item label="账号状态" prop="enable" v-if='isUpdate'>
          <el-radio-group v-model="ruleForm.enable">
            <el-radio label="启用" value="1"></el-radio>
            <el-radio label="停用" value="0"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="ruleForm.remark"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-dialog title="提示" :visible.sync="dialogVisible" width="50%">
      <div>
        <div style="display: flex;justify-content: space-between;">
          <el-input v-model="searchKey"></el-input>
          <el-button type="primary" @click="searchCompany">查询</el-button>
        </div>
        <el-table :data="gridData">
          <el-table-column type="index" label="序号" width="50"></el-table-column>
          <el-table-column property="companyName" label="公司名称" width="200"></el-table-column>
          <el-table-column property="address" label="地址"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button size="mini" @click="handleSelect(scope.$index, scope.row)">选择</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination @size-change="handleSizeChange1" @current-change="handleCurrentChange1" :current-page="currentPage" layout="total, prev, pager, next, jumper" :total="total"></el-pagination>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { hex_md5 } from "@/utils/md5";
import InputSearch from "@/components/InputSearch/InputSearch";
export default {
  inject: ["reload"],
  data() {
    return {
      tables: [],
      defaultVal: [],
      dialogVisible: false,
      searchKey: "",
      formInline: {
        companyName: "",
        searchName: "",
        phone: "",
        companyId: ""
      },
      isAdd: false,
      isUpdate: false,
      ruleForm: {
        username: "",
        remark: "",
        name: "",
        enable: "",
        mobile: "",
        job: "",
        type: "",
        sex: "",
        companyId: "",
        roles: [],
        password: hex_md5("123456"),
        roleIdList: [],
        isAdmin: ''
      },
      rules: {
        username: [
          { required: true, message: "请输入登录名", trigger: "blur" }
        ],
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        type: [{ required: true, message: "请选择角色", trigger: "change" }],

        mobile: [
          { required: true, message: "请输入手机号码", trigger: "blur" }
        ],

        enable: [
          { required: true, message: "请选择账号状态", trigger: "change" }
        ],
        sex: [{ required: true, message: "请选择性别", trigger: "change" }],
        isAdmin: [{ required: true, message: "请选择用户身份", trigger: "change" }],
        // roles: [{
        // type: 'array',
        // required: true,
        // message: '请选择用户角色',
        // trigger: 'change'
        // }],

        // remark: [
        // { required: true, message: '备注信息', trigger: 'blur' }
        // ]
      },
      value5s: "",
      currentPage: 1,
      page: 1,
      limit: 10,
      gridData: [],
      page1: 1,
      limit1: 10,
      searchKey: "",
      total: 0,
      total1: 0,
      showError: false,
      roleList: [],
      inputSearchData: []
    };
  },
  created() {},
  mounted() {
    this.initList();
  },
  methods: {
    getValue(val) {
      console.log(val);
    },
    getAllRole() {
      this.$common.$ajax("/sys/role/selectAll", {}, "get").then(res => {
        // this.roleList = res.data.body;
        this.ruleForm.roles = res.data.body;
      });
    },
    initList() {
      this.$common
        .$ajax(
          "/sys/user/list", {
            page: this.page,
            limit: this.limit,
            mobile: this.formInline.phone,
            name: this.formInline.searchName,
            companyId: this.formInline.companyId
          },
          "get"
        )
        .then(res => {
          console.log(res.data);
          this.tables = res.data.body.list;
          this.total1 = res.data.body.totalCount;
        })
        .catch(err => {
          alert(err);
        });
    },
    showCompany() {
      this.dialogVisible = true;
      this.$common
        .$ajax(
          "/sys/company/list", {
            page: this.page1,
            limit: this.limit1
          },
          "get"
        )
        .then(res => {
          console.log(res.data);
          this.gridData = res.data.body.list;
          this.total = res.data.body.totalCount;
        })
        .catch(err => {
          alert(err);
        });
    },
    searchCompany() {
      this.$common
        .$ajax(
          "/sys/company/list", {
            page: this.page1,
            limit: this.limit1,
            companyName: this.searchKey
          },
          "get"
        )
        .then(res => {
          console.log(res.data);
          this.gridData = res.data.body.list;
          this.total = res.data.body.totalCount;
        })
        .catch(err => {
          alert(err);
        });
    },
    handleSelect(index, item) {
      console.log(index, item);
      this.formInline.companyName = item.companyName;
      this.formInline.companyId = item.id;
      this.ruleForm.companyId = item.id;
      // sessionStorage.selectCompanyId = item.id;
      this.showError = false;
      this.dialogVisible = false;
    },
    addUser() {
      // this.$router.push({ path: '/main/userManage?type=add' })
      this.$common.$ajax("/sys/role/selectAll", {}, "get").then(res => {
        this.ruleForm.roles = res.data.body;
      });

      this.getAllRole();
      this.isAdd = true;
      this.isUpdate = false;
      for (let i in this.ruleForm) {
        if (this.ruleForm[i] != "") {
          this.ruleForm[i] = "";
        }
      }
    },

    onSubmit() {
      this.initList();
    },
    handleClick(row) {
      console.log(row);
    },
    handleSizeChange(val) {
      this.limit = val;
      this.initList();
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page = val;
      this.initList();
    },
    getSelectRole(val) {
      this.ruleForm.roleIdList = val;
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (this.formInline.companyName == "") {
          this.showError = true;
        }
        if (valid) {
          console.log(this.ruleForm);
          // Object.keys(this.ruleForm)

          if (!this.isUpdate) {
            // this.ruleForm.enable = this.ruleForm.enable === "启用" ? 1 : 0;
            this.ruleForm.sex = this.ruleForm.sex === "男" ? 1 : 0;
            this.ruleForm.isAdmin = this.ruleForm.isAdmin === "普通用户" ? 0 : 2;
            delete this.ruleForm.roles;
            this.$common
              .$ajax("/sys/user/save", this.ruleForm, "post")
              .then(res => {
                this.$message({
                  type: "success",
                  message: "添加成功"
                });
                this.isAdd = false;
                this.reload();
              })
              .catch(err => {
                alert(err);
              });
          }
          if (this.isUpdate) {
            this.ruleForm.enable = this.ruleForm.enable === "启用" ? 1 : 0;
            this.ruleForm.sex = this.ruleForm.sex === "男" ? 1 : 0;
            this.ruleForm.isAdmin = this.ruleForm.isAdmin === "普通用户" ? 0 : 2;
            this.$common
              .$ajax("/sys/user/update", this.ruleForm, "post")
              .then(res => {
                this.$message({
                  type: "success",
                  message: "修改成功"
                });
                this.isAdd = false;
                // this.$router.go(0)
                this.reload();
              })
              .catch(err => {
                alert(arr);
              });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    goBack() {
      this.isAdd = false;
      // this.$router.push('/main/userManage')
      this.reload();
    },
    resetForm(formName) {
      if (this.$refs[formName] !== undefined) {
        this.$refs[formName].resetFields();
      }

      this.formInline.searchName = "";
      this.formInline.companyName = "";
      this.formInline.phone = "";
      this.formInline.searchNames = "";
      this.formInline.companyId = "";
      this.initList();
    },
    handleDelet(row) {
      console.log(row);
      // let datas = JSON.stringify([])
      this.$confirm("此操作将永久删除该选项, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
        .then(() => {
          this.$common.$ajax("/sys/user/delete", [row.id], "post").then(res => {
            if (res.data.status === 200) {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              this.reload();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    handleUpdate(row) {
      this.$common.$ajax("/sys/role/selectAll", {}, "get").then(res => {
        this.ruleForm.roles = res.data.body;
      });
      this.defaultVal = row.roles.map(item => {
        return item.id;
      });
      this.ruleForm.roleIdList = this.defaultVal;
      this.isAdd = true;
      this.isUpdate = true;
      row.enable = row.enable === 1 ? "启用" : "停用";
      row.sex = row.sex === 1 ? "男" : "女";
      row.isAdmin = row.isAdmin === 0 ? "管理员" : "普通用户";
      this.ruleForm = row;
      this.formInline.companyName = row.companyName;
    },
    handleInitial(row) {
      this.$confirm("此操作将重置该账号密码, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
        .then(() => {
          this.$common
            .$ajax(
              "/sys/user/initPassword", {
                userId: row.id
              },
              "get"
            )
            .then(res => {
              if (res.data.status === 200) {
                this.$message({
                  type: "success",
                  message: "操作成功!"
                });
                this.reload();
              }
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消重置"
          });
        });
    },
    handleStopAccount(row, type) {
      this.$confirm("此操作将立即生效, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
        .then(() => {
          this.$common
            .$ajax(
              "/sys/user/stopAccount", {
                userId: row.id,
                type: type
              },
              "get"
            )
            .then(res => {
              if (res.data.status === 200) {
                this.$message({
                  type: "success",
                  message: "操作成功!"
                });
                // this.$router.go(0)
                this.reload();
              }
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    handleSizeChange1(val) {
      console.log(`每页 ${val} 条`);
      this.limit1 = val;
      this.searchCompany();
    },
    handleCurrentChange1(val) {
      console.log(`当前页: ${val}`);

      this.page1 = val;
      this.searchCompany;
    }
  },
  components: {
    InputSearch
  }
};

</script>
<style lang="scss">
.order {
  padding-top: 30px;
}

.tables {
  margin-top: 20px;
}

.addBtn {
  height: 40px !important;
}

.err {
  border-color: #f56c6c !important;
}

</style>
